import React, {useCallback} from 'react';
import {LogoutOutlined, SettingOutlined, UserOutlined} from '@ant-design/icons';
import {Avatar, Menu} from 'antd';
// import { stringify } from 'querystring';
import HeaderDropdown from '../HeaderDropdown';
import './index.less';
import type {MenuInfo} from 'rc-menu/lib/interface';
import {outLogin} from "@/services/user/api";

export type GlobalHeaderRightProps = {
    menu?: boolean;
};

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
    await outLogin();

    // const { query = {}, search, pathname } = history.location;
    // const { redirect } = query;
    // Note: There may be security issues, please note
    // if (window.location.pathname !== '/user/login' && !redirect) {
    //   history.replace({
    //     pathname: '/user/login',
    //     search: stringify({
    //       redirect: pathname + search,
    //     }),
    //   });
    // }
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({menu}) => {
    // 初始化

    const onMenuClick = useCallback(
        (event: MenuInfo) => {
            const {key} = event;
            if (key === 'logout') {
                // setInitialState((s) => ({ ...s, currentUser: undefined }));
                loginOut();
                return;
            }
            // history.push(`/account/${key}`);
        },
        [],
    );

    // const loading = (
    //   <span className= "action account">
    //     <Spin
    //       size="small"
    //       style={{
    //         marginLeft: 8,
    //         marginRight: 8,
    //       }}
    //     />
    //   </span>
    // );

    // if (!initialState) {
    //   return loading;
    // }
    //
    // const { currentUser } = initialState;
    //
    // if (!currentUser || !currentUser.name) {
    //   return loading;
    // }

    const menuHeaderDropdown = (
        <Menu className="menu" selectedKeys={[]} onClick={onMenuClick}>
            {menu && (
                <Menu.Item key="center">
                    <UserOutlined/>
                    个人中心
                </Menu.Item>
            )}
            {menu && (
                <Menu.Item key="settings">
                    <SettingOutlined/>
                    个人设置
                </Menu.Item>
            )}
            {menu && <Menu.Divider/>}

            <Menu.Item key="logout">
                <LogoutOutlined/>
                退出登录
            </Menu.Item>
        </Menu>
    );
    return (
        <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className="action account">
        <Avatar size="small" className="avatar" src="#" alt="avatar"/>
          {/*<Avatar size="small" className="avatar" src={currentUser.avatar} alt="avatar" />*/}
          {/*<span className="name antiocn">{currentUser.name}</span>*/}
          <span className="name antiocn">张煊信</span>
      </span>
        </HeaderDropdown>
    );
};

export default AvatarDropdown;
